package ywpt.web.action.config;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts2.ServletActionContext;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import ywpt.components.acegi.domain.Operation;
import ywpt.core.Constants;
import ywpt.core.SystemMessage;

import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.util.StringTools;
import ywpt.core.web.BaseAction;
import ywpt.model.WeixinAccount;
import  com.ifp.weixin.MessageMng.Message.resp.RespArticleInfoDefine;
import ywpt.model.ProjectPeople;
import ywpt.service.config.ArticleService;
import ywpt.web.common.OperationConstants;
import ywpt.web.common.PublicFunction;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.sina.sae.storage.SaeStorage;
import com.sina.sae.util.SaeUserInfo;

public class ArticleAction extends BaseAction implements ModelDriven<RespArticleInfoDefine>, Preparable{

	/**
	 * 微信文章管理Action
	 */
	private static final long serialVersionUID = 3076499333666668439L;

	protected static int DEFAULT_PAGE_SIZE	=100;
	private Long id;
	private RespArticleInfoDefine respArticleInfo;
	private List<RespArticleInfoDefine> rspList = new ArrayList<RespArticleInfoDefine>();
	private ArticleService  articleService;
	private int version;
	
	private Long respMsgId;
	private String respMsgTitle;
	private Long weixinAccountId;
	private String weixinAccountName;
	private Long unit_id;
	private String unit_name;
	
	private File upload;// 实际上传文件
	private String uploadFileName; // 上传文件名	
	
	
	//查询相关
	private Long qunit_id;
	
	private String qName;  //微信号名称
	private String qTitle;//微信文章标题

	private String picUrl;

	/**
	 * @return id
	 */
	public Long getId() {
		return id;
	}
	/**
	 * @param id 要设置的 id
	 */
	public void setId(Long id) {
		this.id = id;
	}
	/**
	 * @return is_Certified
	 */



	/**
	 * @return qName
	 */
	public String getQName() {
		return qName;
	}
	/**
	 * @param name 要设置的 qName
	 */
	public void setQName(String name) {
		qName = name;
	}
	/**
	 * @return qunit_id
	 */
	public Long getQunit_id() {
		return qunit_id;
	}
	/**
	 * @param qunit_id 要设置的 qunit_id
	 */
	public void setQunit_id(Long qunit_id) {
		this.qunit_id = qunit_id;
	}

	/**
	 * @return unit_id
	 */
	public Long getUnit_id() {
		return unit_id;
	}
	/**
	 * @param unit_id 要设置的 unit_id
	 */
	public void setUnit_id(Long unit_id) {
		this.unit_id = unit_id;
	}
	/**
	 * @return unit_name
	 */
	public String getUnit_name() {
		return unit_name;
	}
	/**
	 * @param unit_name 要设置的 unit_name
	 */
	public void setUnit_name(String unit_name) {
		this.unit_name = unit_name;
	}
	/**
	 * @return version
	 */
	public int getVersion() {
		return version;
	}
	/**
	 * @param version 要设置的 version
	 */
	public void setVersion(int version) {
		this.version = version;
	}
	/**
	 * @return weixin_type
	 */


	public RespArticleInfoDefine getModel() {
		// TODO 自动生成方法存根
		return this.respArticleInfo;
	}
	
	public void prepare() throws Exception {
		// TODO 自动生成方法存根
		if(id!=null){
			this.respArticleInfo = this.articleService.getArticleById( id );
		}else{
			this.respArticleInfo = new RespArticleInfoDefine();
		}
	
	}


	public String list() throws Exception {

		DetachedCriteria query = DetachedCriteria.forClass(RespArticleInfoDefine.class);
		getDataList(query);
		return SUCCESS;
	}

	/*按页获取有效数据*/
	protected void getDataList(DetachedCriteria query ){
		
		List<RespArticleInfoDefine> result = new ArrayList<RespArticleInfoDefine>();
		query.add(Restrictions.eq("delete_Flag", false));
		int totalRows=RequestUtils.getTotalRowsFromRequest(getRequest());
		if(totalRows<0)
		{
			totalRows= articleService.getArticleCountByCriteria(query);
		}
		int[] rowStartEnd=RequestUtils.getRowStartEnd(getRequest(),totalRows,DEFAULT_PAGE_SIZE,0);
		query.addOrder(Order.asc("id"));
		query.setProjection(null);
		Limit limit=RequestUtils.getLimit(getRequest(),"ec",totalRows,DEFAULT_PAGE_SIZE);
		int pageSize=limit.getCurrentRowsDisplayed();
		
		result.addAll((articleService.getArticleInfos(query, pageSize, rowStartEnd[0])));
		
		rspList.addAll(result);
		
/*		System.out.println("rspList.size()="+rspList.size());
		Iterator it = rspList.iterator();
		while ( it.hasNext() ) {
			RespArticleInfoDefine rsp= (RespArticleInfoDefine)it.next();
			System.out.println("rsp.id="+rsp.getId());
			System.out.println("rsp.title="+rsp.getTitle());
			System.out.println("rsp.description="+rsp.getDescription());
			System.out.println("rsp.insert_Time="+rsp.getInsert_Time());
			System.out.println("rsp.delete_flag="+rsp.getDelete_Flag());
			System.out.println("rsp.publish_flag="+rsp.getPublish_Flag());
			System.out.println("rsp.version="+rsp.getVersion());
			System.out.println("rsp.unitInfo="+rsp.getWeixinAccount().getUnitInfo().getUnit_name());
			System.out.println("rsp.respMsgInfoDefine.Title="+rsp.getRespMsgInfoDefine().getTitle());
			System.out.println("rsp.respMsgInfoDefine.Content="+rsp.getRespMsgInfoDefine().getContent());
		}*/
		
		limit = RequestUtils.getLimit(getRequest(),"ec",result.size(),DEFAULT_PAGE_SIZE);
	}
	
	public String input(){
		return INPUT;
	}
	

	public String save() throws Exception
	{	System.out.println("into save*************** ");
		try {
			System.out.println("ArticleAction save id= "+id);
			if (id == null) {
				if( (upload!=null) && (upload.exists()) ){
					respArticleInfo.setPicUrl(uploadArticleImg(upload));
				}else {
					respArticleInfo.setPicUrl(picUrl);
				}
				respArticleInfo.setInsert_oper(this.getCurrentUser());
				respArticleInfo.setInsert_Time(new Date());

				articleService.saveArticleInfo(respArticleInfo,
						respMsgId, weixinAccountId);
				this.addActionMessage(SystemMessage.SAVE_SUCCESS);
			} else {
				if (this.getVersion() == respArticleInfo.getVersion()) {
					if( (upload!=null) && (upload.exists()) ){
						respArticleInfo.setPicUrl(uploadArticleImg(upload));
					}else {
						respArticleInfo.setPicUrl(picUrl);
					}
					respArticleInfo.setUpdate_oper(this.getCurrentUser());
					respArticleInfo.setUpdate_Time(new Date());
					articleService.updateArticleInfo(respArticleInfo,
							respMsgId, weixinAccountId );
					this.addActionMessage(SystemMessage.UPDATE_SUCCESS);

				} else
					this.addActionMessage(SystemMessage.UPDATE_FAIL);
			}
		} catch (UniqueConstraintException e) {
			this.addActionError(SystemMessage.SAVE_FAIL + e.getMessage());
			return SUCCESS;
		}
		showInfo();	
		
		return SUCCESS;
	}

		
	protected void showInfo() {
		if(this.respArticleInfo.getRespMsgInfoDefine()!=null) {
			this.respMsgId = this.respArticleInfo.getRespMsgInfoDefine().getId();
			this.respMsgTitle = this.respArticleInfo.getRespMsgInfoDefine().getTitle();
		}
		
		if(this.respArticleInfo.getWeixinAccount()!=null) {
			this.weixinAccountId = this.respArticleInfo.getWeixinAccount().getId();
			this.weixinAccountName = this.respArticleInfo.getWeixinAccount().getName();
			this.unit_id = this.respArticleInfo.getWeixinAccount().getUnitInfo().getId();
			this.unit_name = this.respArticleInfo.getWeixinAccount().getUnitInfo().getUnit_name();	
			
		}
	}
	
	public String edit(){
		respArticleInfo = articleService.getArticleById(id);
		showInfo();
		return INPUT;
	}
	public String content(){
		respArticleInfo = articleService.getArticleById(id);
		showInfo();
		return INPUT;
	}
	public String delete() {
		if (id != null) {
			try {
				respArticleInfo = this.articleService.getArticleById(id);
				respArticleInfo.setUpdate_oper(this.getCurrentUser());
				respArticleInfo.setUpdate_Time(new Date());
				respArticleInfo.setDelete_Flag(true);
				articleService.saveArticleInfo( respArticleInfo);
			}
			catch (UniqueConstraintException e) {
				this.addActionMessage("删除失败！" + e.getMessage());
				return INPUT;
			}
		} else {
			this.addActionMessage(SystemMessage.NO_OBJECT);
			return INPUT;
		}
		return SUCCESS;
	}
	

	public String search() {
		DetachedCriteria query = DetachedCriteria.forClass(RespArticleInfoDefine.class);
			if (!StringTools.isNullOrSpace(this.qTitle)) {
				query.add(Restrictions.like("title", "%"+this.qTitle+"%"));
			}

			if  ((!StringTools.isNullOrSpace(this.qName))||(this.qunit_id!=null)) {
				query.createAlias("weixinAccount", "weixinAccount");
			}
			if  (!StringTools.isNullOrSpace(this.qName)) {
				query.add(Restrictions.like("weixinAccount.name", "%"+this.qName+"%"));
			}
			if (this.qunit_id!=null) {
				query.add(Restrictions.eq("weixinAccount.unitInfo.id", this.qunit_id));
			}
		getDataList(query);
		return SUCCESS;
	}

	public String select() 
	{
		rspList.addAll(articleService.getArticleInfos());
		return SUCCESS;
	}
	/**
	 * @return articleService
	 */
	public ArticleService getArticleService() {
		return articleService;
	}
	/**
	 * @param articleService 要设置的 articleService
	 */
	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}
	/**
	 * @return qTitle
	 */
	public String getQTitle() {
		return qTitle;
	}
	/**
	 * @param title 要设置的 qTitle
	 */
	public void setQTitle(String title) {
		qTitle = title;
	}
	/**
	 * @return respArticleInfo
	 */
	public RespArticleInfoDefine getRespArticleInfoDefine() {
		return respArticleInfo;
	}
	/**
	 * @param respArticleInfo 要设置的 respArticleInfo
	 */
	public void setRespArticleInfoDefine(RespArticleInfoDefine respArticleInfo) {
		this.respArticleInfo = respArticleInfo;
	}
	/**
	 * @return respMsgId
	 */
	public Long getRespMsgId() {
		return respMsgId;
	}
	/**
	 * @param respMsgId 要设置的 respMsgId
	 */
	public void setRespMsgId(Long respMsgId) {
		this.respMsgId = respMsgId;
	}
	/**
	 * @return respMsgTitle
	 */
	public String getRespMsgTitle() {
		return respMsgTitle;
	}
	/**
	 * @param respMsgTitle 要设置的 respMsgTitle
	 */
	public void setRespMsgTitle(String respMsgTitle) {
		this.respMsgTitle = respMsgTitle;
	}
	/**
	 * @return rspList
	 */
	public List<RespArticleInfoDefine> getRspList() {
		return rspList;
	}
	/**
	 * @param rspList 要设置的 rspList
	 */
	public void setRspList(List<RespArticleInfoDefine> rspList) {
		this.rspList = rspList;
	}
	/**
	 * @return weixinAccountId
	 */
	public Long getWeixinAccountId() {
		return weixinAccountId;
	}
	/**
	 * @param weixinAccountId 要设置的 weixinAccountId
	 */
	public void setWeixinAccountId(Long weixinAccountId) {
		this.weixinAccountId = weixinAccountId;
	}
	/**
	 * @return weixinAccountName
	 */
	public String getWeixinAccountName() {
		return weixinAccountName;
	}
	/**
	 * @param weixinAccountName 要设置的 weixinAccountName
	 */
	public void setWeixinAccountName(String weixinAccountName) {
		this.weixinAccountName = weixinAccountName;
	}	

	public String uploadArticleImg(File upload )throws Exception{
		try {
			String publish_typeString =this.getPublishType();
			if ("local".equals(publish_typeString)) {
				return uploadArticleImgtoLocal( upload );
			} else {
				return uploadArticleImgtoSae( upload );
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError(e.getMessage());
			return null;
		}
	}
	private String uploadArticleImgtoSae1(File upload2) throws Exception{
		System.out.println("into uploadArticleImgtoSae1");
		// TODO 自动生成方法存根
		HttpServletRequest request;
		request=this.getRequest();
		String RandomString =UUID.randomUUID().toString();
		String path="";
		try {
			FileInputStream fis = new FileInputStream(upload2); 
			int filelong = fis.available(); 
			System.out.println("filelong = "+filelong);
			byte[] long_buf = new byte[filelong]; 
			fis.read(long_buf); 
            // 上传完毕后 使用SaeStorage往storage里面写
            SaeStorage ss = new SaeStorage();
            System.out.println("SaeStorage wirte begin!!!");
            ss.write("article", RandomString+getExt(uploadFileName),long_buf);
            System.out.println("SaeStorage wirte end!!!");
            // 使用upload方法上传到域domain下，此处本人的是
            // 获取上传后的图片路径
            path = ss.getUrl("article", RandomString+getExt(uploadFileName));
            System.out.println("path="+path);
			return path;
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError(e.getMessage());
			return null;
		}
	}
	
	private String uploadArticleImgtoSae(File upload2) throws Exception{
		// TODO 自动生成方法存根
		System.out.println("into uploadArticleImgtoSae");
		HttpServletRequest request;
		request=this.getRequest();
		String RandomString =UUID.randomUUID().toString();
		String path="";
		try {
			String realPath = SaeUserInfo.getSaeTmpPath() + "/";
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) return null;
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(1024 * 1024 * 5);	
			List<FileItem> items = null;
			items = upload.parseRequest(request);
			for (FileItem item : items) {
                if (!item.isFormField()) {
                    File fullFile = new File(item.getName());
                    File uploadFile = new File(realPath, fullFile.getName());
                    item.write(uploadFile);
                    // 上传完毕后 使用SaeStorage往storage里面写
                    SaeStorage ss = new SaeStorage();
                    // 使用upload方法上传到域domain下，此处本人的是
                    ss.upload("article", realPath + fullFile.getName(),RandomString+getExt( fullFile.getName()));
                    // 获取上传后的图片路径
                    path = ss.getUrl("article", RandomString+getExt( fullFile.getName()) );
                }
            }
			System.out.println("path = "+path);
			return path;
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError(e.getMessage());
			return null;
		}
	}
	public String uploadArticleImgtoLocal(File upload )throws Exception{
		System.out.println("into uploadArticleImgtoLocal");
		try {
			String urlString = "../../ArticleImg/";
			String url = ServletActionContext.getServletContext().getRealPath("/ArticleImg/");			
			File file_date = new File(url);
				if(!file_date.exists()){
					file_date.mkdirs();
				}
			String fileName = uploadFileName;
			String realName = UUID.randomUUID().toString() + getExt(fileName);
			File target = new File(url, realName);
			FileUtils.copyFile(upload, target);
			return (urlString+realName);
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError(e.getMessage());
			return null;
		}
	}	
	
	
	public static String getExt(String fileName) {
		if(fileName.lastIndexOf(".")>=0)
			return fileName.substring(fileName.lastIndexOf("."));
		else
			return "";
	}
	/**
	 * @return respArticleInfo
	 */
	public RespArticleInfoDefine getRespArticleInfo() {
		return respArticleInfo;
	}
	/**
	 * @param respArticleInfo 要设置的 respArticleInfo
	 */
	public void setRespArticleInfo(RespArticleInfoDefine respArticleInfo) {
		this.respArticleInfo = respArticleInfo;
	}
	/**
	 * @return upload
	 */
	public File getUpload() {
		return upload;
	}
	/**
	 * @param upload 要设置的 upload
	 */
	public void setUpload(File upload) {
		this.upload = upload;
	}
	/**
	 * @return uploadFileName
	 */
	public String getUploadFileName() {
		return uploadFileName;
	}
	/**
	 * @param uploadFileName 要设置的 uploadFileName
	 */
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	/**
	 * @return picUrl
	 */
	public String getPicUrl() {
		return picUrl;
	}
	/**
	 * @param picUrl 要设置的 picUrl
	 */
	public void setPicUrl(String picUrl) {
		this.picUrl = picUrl;
	}		
}